package com.fortune.cat.manager;

import com.fortune.cat.constant.ZkPathConstants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhaozeyang
 * @date 2019/4/28 10:35
 * @description
 */
@Component
public class SignAccessManager implements InitializingBean {

    private final static Map<String, String> ACCESS_MAP = new ConcurrentHashMap<>();

    private final ZkClient zkClient;

    private final Gson gson = new Gson();

    public SignAccessManager(ZkClient zkClient) {
        this.zkClient = zkClient;
    }

    public  String getAccessKeyById(String accessId) {
        return ACCESS_MAP.get(accessId);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        loadAccessInfo();
    }

    private void loadAccessInfo() {
        final String routeParent = ZkPathConstants.SIGN_ACCESS;
        //判断跟节点如果不存在就创建
        if (!zkClient.exists(routeParent)) {
            zkClient.createPersistent(routeParent, true);
        }
        loadAccess(routeParent);
        zkClient.subscribeDataChanges(routeParent, new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) {
                loadAccess(routeParent);
            }

            @Override
            public void handleDataDeleted(String dataPath) {

            }
        });
    }

    private void loadAccess(String routeParent) {
        String mapStr = zkClient.readData(routeParent);
        if (StringUtils.isNotBlank(mapStr)) {
            ACCESS_MAP.putAll(gson.fromJson(mapStr, new TypeToken<Map<String, String>>() {
            }.getType()));
        }
    }
}
